package com.shigu.weixin.service;


import com.opentae.data.mall.beans.PayWxApply;
import com.opentae.data.mall.beans.WxRefund;
import com.opentae.data.mall.examples.PayWxApplyExample;
import com.opentae.data.mall.interfaces.ManagerMallUserMapper;
import com.opentae.data.mall.interfaces.PayWxApplyMapper;
import com.opentae.data.mall.interfaces.UserWxInfoMapper;
import com.opentae.data.mall.interfaces.WxRefundMapper;
import com.shigu.util.MoneyUtil;
import com.shigu.weixin.enums.WxConfigSource;
import com.shigu.weixin.vo.AppPayVo;
import com.shigu.weixin.vo.JSAPIVo;
import com.shigu.weixin.vo.WxRefundVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


/**
 * @author 郭尔
 * @description 微信支付申请处理
 * @date 2019/1/15 13:44
 */
@Service
public class PayApplyService {
    private static final Logger logger = LoggerFactory.getLogger(PayApplyService.class);

    @Autowired
    WxPayService wxPayService;
    @Autowired
    PayWxApplyMapper payWxApplyMapper;
    @Autowired
    ManagerMallUserMapper managerMallUserMapper;
    @Autowired
    UserWxInfoMapper userWxInfoMapper;
    @Autowired
    WxRefundMapper wxRefundMapper;


    /**
     * 获取JSAPI支付参数
     *
     * @param tradeCode 交易编号
     * @description
     * @author 郭尔
     * @date 2019/1/15 13:32
     */
    public JSAPIVo applyWxPay(Long userId, Double amount, String tradeCode, WxConfigSource source) throws Exception {
        String openId = "";
        switch (source) {
            case XCX:
                openId = userWxInfoMapper.selXcxOpeniid(userId);
                break;
            case GZH:
                openId = userWxInfoMapper.selGzhOpeniid(userId);
                break;
        }
        //如果已存在此编号则删除之前的，插入新的，以免处理时产生错误
        PayWxApplyExample example = new PayWxApplyExample();
        example.createCriteria().andTradeNoEqualTo(tradeCode);
        payWxApplyMapper.deleteByExample(example);

        PayWxApply apply = new PayWxApply();
        apply.setApplyTime(new Date());
        apply.setMoney(MoneyUtil.formatPriceMoney(amount));
        apply.setUserId(userId);
        payWxApplyMapper.insertSelective(apply);
        apply.setTradeNo(tradeCode);
        payWxApplyMapper.updateByPrimaryKeySelective(apply);

        JSAPIVo jsapiVo = wxPayService.JSAPIPay(apply.getTradeNo(), MoneyUtil.formatMoneyDouble(amount),
                "127.0.0.1", openId, source);
        payWxApplyMapper.updateByPrimaryKeySelective(apply);
        return jsapiVo;
    }


    /**
     * @description 处理微信申请
     * @author 郭尔
     * @date 2019/1/15 13:52
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean dowithPayApply(String return_code, String return_msg, String money, String transaction_id, String out_trade_no) {
        PayWxApplyExample example = new PayWxApplyExample();
        example.createCriteria().andTradeNoEqualTo(out_trade_no);
        if (!return_code.equals("SUCCESS")) {
            PayWxApply apply = new PayWxApply();
            apply.setStatus(1);
            apply.setErrReason(return_msg);
            payWxApplyMapper.updateByExampleSelective(apply, example);
            return false;
        }
        example.createCriteria().andStatusEqualTo(0);
        example.setStartIndex(0);
        example.setEndIndex(1);
        List<PayWxApply> applies = payWxApplyMapper.selectByConditionList(example);
        if (applies.size() == 0) {
            logger.error(transaction_id + "支付无效，" + out_trade_no + "订单不匹配");
            return false;
        }
        Double dmoney = Double.valueOf(money);
        dmoney = dmoney / 100;
        PayWxApply apply = applies.get(0);
        apply.setWxNo(transaction_id);
        apply.setStatus(1);
        apply.setRealPayMoney(MoneyUtil.formatMoney(dmoney));
        payWxApplyMapper.updateByPrimaryKeySelective(apply);
        return true;
    }


    /**
     * @description app申请微信支付
     * @author 郭尔
     * @date 2019/2/20 10:00
     */
    public AppPayVo appWxPay(Long userId, String amount, String tradeCode) throws Exception {
        PayWxApplyExample example = new PayWxApplyExample();
        example.createCriteria().andTradeNoEqualTo(tradeCode);
        payWxApplyMapper.deleteByExample(example);

        PayWxApply apply = new PayWxApply();
        apply.setApplyTime(new Date());
        apply.setMoney(amount);
        apply.setUserId(userId);
        payWxApplyMapper.insertSelective(apply);
        apply.setTradeNo(tradeCode);
        payWxApplyMapper.updateByPrimaryKeySelective(apply);
        AppPayVo appPayVo = wxPayService.appPay(apply.getTradeNo(), Double.valueOf(amount), "127.0.0.1");
        payWxApplyMapper.updateByPrimaryKeySelective(apply);
        return appPayVo;
    }

    /**
     * @description 购买vip
     * @author 郭尔
     * @date 2019/2/20 10:00
     */
    public AppPayVo payVip(Long userId, String amount) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");

        PayWxApply apply = new PayWxApply();
        apply.setApplyTime(new Date());
        apply.setMoney(amount);
        apply.setUserId(userId);
        payWxApplyMapper.insertSelective(apply);
        DecimalFormat df = new DecimalFormat("000000");
        String outTradeCode = sdf.format(new Date())+df.format(apply.getApplyId());
        apply.setTradeNo(outTradeCode);
        payWxApplyMapper.updateByPrimaryKeySelective(apply);

        AppPayVo appPayVo = wxPayService.vipPurchase(apply.getTradeNo(), Double.valueOf(amount), "127.0.0.1");
        payWxApplyMapper.updateByPrimaryKeySelective(apply);
        return appPayVo;
    }

    /**
    *
    * @return WxRefundId 退款id
    *
    * @Author 过儿
    * @Date 2019/12/18
    */
    public void wxRefund(Double amount, String tradeCode,int source) throws Exception {
        PayWxApplyExample example = new PayWxApplyExample();
        example.createCriteria().andTradeNoEqualTo(tradeCode);
        example.setStartIndex(0);
        example.setEndIndex(1);
        List<PayWxApply> applies = payWxApplyMapper.selectByConditionList(example);
        if(!applies.isEmpty()){
            PayWxApply apply = applies.get(0);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");

            WxRefund refund = new WxRefund();
            refund.setCreateTime(new Date());
            refund.setMoney(amount.toString());
            refund.setStatus(false);
            refund.setTradeCode(tradeCode);
            refund.setWxNo(apply.getWxNo());
            wxRefundMapper.insertSelective(refund);

            String refundCode =  sdf.format(new Date())+refund.getWxRefundId();
            refund.setRefundCode(refundCode);
            WxRefundVo vo = wxPayService.refund(refundCode, amount, apply.getWxNo(),source);
            refund.setStatus(vo.getSuccess());
            if(vo.getSuccess()){
                //保存微信的退款id
                refund.setRefundId(vo.getRefundId());
            }else {
                refund.setMsg(vo.getMsg());
            }
            wxRefundMapper.updateByPrimaryKeySelective(refund);
        }
    }


}
